package com.sgb.kjwl.view.ui.activity.self.shop;

import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.im.immodel.IMUtils;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.goods.entity.GoodsAttrEntity;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.entity.GoodsSkuSelectResultEntity;
import com.sgb.goods.entity.inquiry.InquiryDetailsEntity;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BuildConfig;
import com.sgb.kjwl.GoodsWebView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityGoodsDetail2Binding;
import com.sgb.kjwl.di.material.DaggerMaterialComponent;
import com.sgb.kjwl.di.material.MaterialModule;
import com.sgb.kjwl.model.EnquiryImAlternateEntity;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.model.entity.CallPhoneEntity;
import com.sgb.kjwl.model.entity.CompanyDetailsEntity;
import com.sgb.kjwl.model.entity.GoodsSkuDetailEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.MaterialCompanyEntity;
import com.sgb.kjwl.model.entity.ShoppingCarRequest;
import com.sgb.kjwl.model.entity.SkuCheckEntity;
import com.sgb.kjwl.model.entity.SkuCombinationEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.model.entity.shopping.ShoppingCarResponse;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.RecommendListEntity;
import com.sgb.kjwl.model.entity.user.SkuItemAttrEntity;
import com.sgb.kjwl.pop.ParamsPop;
import com.sgb.kjwl.utils.ConfigUtils;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.ShoppingCartActivity;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.StatementActivity;
import com.sgb.kjwl.view.ui.activity.StorageAddressActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.JoinCompanyActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegisterActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.material.GoodsSkuAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.AttrAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.GoodsDetailAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.ParamsAdapter;
import com.sgb.kjwl.view.widget.CallPhonePopWindow;
import com.sgb.kjwl.view.widget.GoodSSkuWindow;
import com.sgb.kjwl.view.widget.GoodsAddWindow;
import com.sgb.kjwl.view.widget.ThreeButtonDialog;
import com.sgb.kjwl.view.widget.lease.common.RecyclerViewUtils;
import com.sgb.kjwl.view.widget.self.permission.UserPermissionUtils;
import com.sgb.kjwl.viewmodel.material.ShopGoodsDetailModel;
import com.sgb.link.event.MaterialEvent;
import com.sgb.member.MemberConfig;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.PersonApplyJoinActivity;
import com.sgb.member.ui.activity.PersonInviteJoinActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MessageEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.UiUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.view.entity.GoodsPublishEntity;
import com.swgk.core.xrecyclerview.AppBarStateChangeListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import cn.jzvd.Jzvd;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

/****
 * @author Administrator
 * 商品详情
 */
public class ShopGoodsDetailActivity extends AppActivity {
    private ActivityGoodsDetail2Binding binding;
    @Inject
    ShopGoodsDetailModel viewModel;
    /***
     * 商品id
     */
    public String shopId;
    public static String skuId;
    private String companyId;
    private String companyNo = "";

    private GoodSSkuWindow goodSSkuWindow;
    public boolean isFirst;
    private double itemNum = 1;
    /**
     * 视频
     */
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private final String[] titleName = new String[]{"商品", "详情", "推荐"};

    /**
     * 闪验
     */
    static final String[] PERMISSIONS = new String[]{Manifest.permission.READ_PHONE_STATE};
    private GoodsSkuAdapter goodsSkuAdapter;
    boolean userFocusCompanyStatus;
    boolean userFocusStatus;
    public GoodsSkuDetailEntity data;
    private int mLastIndex;
    private List<String> mSelect;
    private AttrAdapter mAttrAdapter;
    private List<String> mVideos;
    List<SkuItemAttrEntity> sku = new ArrayList<>();
    /***
     * 供应商详情
     */
    private CompanyDetailsEntity companyDetailsEntity;
    /****
     * 商品发布时的详情
     */
    private GoodsPublishEntity goodsPublishEntity;


    private static final String Success = "SUCCESS";

    private int lastPosition = -1; //用于判断recyclerView滑动的时候 是不是同一个item的位置
    private int mTabPosition = -1; //点击的tab的position
    private boolean isRecyclerViewScroll;

    private GoodsDetailAdapter goodsDetailAdapter;

    private List<Bean> indicator = new ArrayList<>();
    private static final int MIN_CLICK_DELAY_TIME = 3000;

    MaterialCompanyEntity companyData;
    QualityMemberBean bean;

    private GoodsAddWindow goodsAddWindow;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMaterialComponent.builder().appComponent(appComponent).materialModule(new MaterialModule(this)).build().inject(this);
    }

    public static void start(Context context, String id, String from, String skuId) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.putExtra("from", from);
        intent.putExtra("skuId", skuId);
        intent.setClass(context, ShopGoodsDetailActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_goods_detail2);
        binding.setViewModel(viewModel);
        goodsDetailAdapter = new GoodsDetailAdapter(ShopGoodsDetailActivity.this, 3, false);
        binding.backView.setOnClickListener(this);
        binding.imageDetailLeft.setOnClickListener(v -> {
            binding.banner.setStopPlay();
            if (mLastIndex > 0) {
                mLastIndex--;
            }
            mHandler.sendEmptyMessage(0);
            mHandler.sendEmptyMessageDelayed(1, MIN_CLICK_DELAY_TIME);
        });
        binding.imageDetailRight.setOnClickListener(v -> {
            binding.banner.setStopPlay();
            mLastIndex++;
            mHandler.sendEmptyMessage(0);
            mHandler.sendEmptyMessageDelayed(1, MIN_CLICK_DELAY_TIME);
        });
        binding.imageIconDetailMore.setOnClickListener(this);
        binding.imageIconDetailBack.setOnClickListener(this);
        binding.backViewToolBar.setOnClickListener(this);
        binding.tvShop.setOnClickListener(this);
        binding.tvJiameng.setOnClickListener(this);
        binding.tvAddShoppingCar.setOnClickListener(this);
        binding.tvPurchase.setOnClickListener(this);
        binding.tvShoppingCar.setOnClickListener(this);
        binding.tvShoppingCarUp.setOnClickListener(this);
        binding.tvMessage.setOnClickListener(this);
        binding.imgShare.setOnClickListener(this);
        binding.imgShareUp.setOnClickListener(this);
        binding.tvInquiry.setOnClickListener(this);
        setToolBar();
        goodSSkuWindow = new GoodSSkuWindow(ShopGoodsDetailActivity.this);
        goodSSkuWindow.setBgView(binding.grayLayout);
        goodSSkuWindow.setOnResultClick((key1, key2, key3) -> {
            itemNum = Double.parseDouble((String) key1);
            GoodsSkuSelectResultEntity entity = (GoodsSkuSelectResultEntity) key3;
            goodsDetailAdapter.setPrice(entity);
        });
        goodsSkuAdapter = new GoodsSkuAdapter(this, null);
        if (UserOperating.getInstance().isLogged()) {
            viewModel.getCarCount();
        }
        binding.recycleView.setLayoutManager(new LinearLayoutManager(ShopGoodsDetailActivity.this));
        binding.recycleView.setAdapter(goodsDetailAdapter);
        initRecyclerview();
        initAppBarChangedListener();
        goodsAddWindow = new GoodsAddWindow(this);
        goodsAddWindow.setBgView(binding.grayLayout);
        //设置点击回调
        goodsAddWindow.setOnResultClick((key1, key2, key3) -> {
            int type = (int) key1;
            if (type == 1) {
                //申请加盟
                if (!MemberApplyJoin("1")) {
                    return;
                }
                if (!MemberConfig.getInstance().isHavePermission("14_shenqingjiameng1")) {//申请加盟权限
                    MToast.showToast(getActivity(), "没有权限操作，请找企业管理员分配权限");
                    return;
                }
                getQualityMemberBean().setApproveType("1");
                int accountType = UserOperating.getInstance().getUserIdentity();
                if (accountType == 0) {
                    PersonApplyJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean(), false);
                } else {
                    MemberApplyJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean());
                }
            } else {
                //邀请加盟
                if (!MemberApplyJoin("2")) {
                    return;
                }
                if (!MemberConfig.getInstance().isHavePermission("14_yaoqinghuiyuan1")) {//邀请加盟权限
                    MToast.showToast(getActivity(), "没有权限操作，请找企业管理员分配权限");
                    return;
                }
                int accountType = UserOperating.getInstance().getUserIdentity();
                getQualityMemberBean().setApproveType("2");
                if (accountType == 0) {
                    PersonInviteJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean(), false);
                } else {
                    MemberInviteJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean());
                }
            }
        });
    }

    private void initAppBarChangedListener() {

        binding.appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.IDLE) {
                    binding.banner.setStartPLAY(false);
//                    binding.imageIconDetailImageBack.setVisibility(View.GONE);
//                    binding.imageIconDetailImageMore.setVisibility(View.GONE);
                    ;
                } else if (state == State.COLLAPSED) {
                    binding.banner.setStopPlay();
//                    binding.imageIconDetailImageBack.setVisibility(View.VISIBLE);
//                    binding.imageIconDetailImageMore.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void init() {
        shopId = getIntent().getStringExtra("id");
        String from = getIntent().getStringExtra("from");
        skuId = getIntent().getStringExtra("skuId");
        viewModel.getRecommendList(shopId, skuId);
        viewModel.getDetailModel(shopId, skuId);
        viewModel.getGoodsItemInformationById(shopId);
        viewModel.getUserFocusStatus(skuId);
        viewModel.getPlatformStatement();
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            viewModel.getAuthInfo();
        }
        if ("SHOPPING_CAR".equals(from)) {
            binding.llBottom.setVisibility(View.GONE);
        } else {
            binding.llBottom.setVisibility(View.VISIBLE);
        }
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }

    private void initTabLayoutTabOnclick() {
        binding.tabGroup.setTabMode(TabLayout.MODE_AUTO);
        binding.tabGroup.clearOnTabSelectedListeners();
        binding.tabGroup.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                mTabPosition = position;
                tipPosition(position);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 滑动到指定位置
     *
     * @param position
     */
    private void tipPosition(int position) {
        if (!isRecyclerViewScroll) {
            LinearLayoutManager mLayoutManager = (LinearLayoutManager) binding.recycleView.getLayoutManager();
            if (mLayoutManager != null) {
                mLayoutManager.scrollToPositionWithOffset(position, 0);
            }
            if (position == 0) {
                binding.appBarLayout.post(() -> {
                    CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) binding.appBarLayout.getLayoutParams();
                    AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) layoutParams.getBehavior();
                    if (behavior != null) {
                        int topAndBottomOffset = behavior.getTopAndBottomOffset();
                        if (topAndBottomOffset != 0) {
                            behavior.setTopAndBottomOffset(0);
                            binding.appBarLayout.setExpanded(true, true);
                        }
                    }
                });
            }
        }
    }

    /**
     * recycleView添加滑动事件
     */
    private void initRecyclerview() {
        binding.recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //获得recyclerView的线性布局管理器
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //获取到第一个item的显示的下标  不等于0表示第一个item处于不可见状态 说明列表没有滑动到顶部 显示回到顶部按钮
                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
                isRecyclerViewScroll = true;
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (isOpening) {
                        isOpening = false;
                    }
                    if (isCloseing) {
                        isCloseing = false;
                    }
                    if (firstVisibleItemPosition == 0) {
                        //回到顶部时，置顶按钮隐藏
//                        binding.top.setVisibility(View.GONE);
                    } else {
                        // 判断是否滚动超过一屏,置顶按钮显示
//                        binding.top.setVisibility(View.VISIBLE);
                        //置顶按钮的点击事件
//                        binding.top.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                //置顶按钮隐藏
//                                binding.top.setVisibility(View.GONE);
//                                //打开APPBar的布局
//                                binding.appBar.setExpanded(true);
//                                //停止滑动
//                                recyclerView.stopScroll();
//                                //返回到顶部
//                                recyclerView.scrollToPosition(0);
//                            }
//                        });
                    }

                    isRecyclerViewScroll = false;

//                    if (objectAnimatorMore != null && objectAnimatorMore.isRunning()) {
//                        objectAnimatorMore.cancel();
//                    }
//                    if (objectAnimatorBack != null && objectAnimatorBack.isRunning()) {
//                        objectAnimatorBack.cancel();
//                    }

//                } else if ((newState == RecyclerView.SCROLL_STATE_DRAGGING) || (newState == RecyclerView.SCROLL_STATE_SETTLING)) {
//
//                }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                try {
                    int currentPosition = RecyclerViewUtils.findFirstVisiblePosition(recyclerView);
                    if (lastPosition != currentPosition) {
                        lastPosition = currentPosition;
                        //要滑动的时候 去判断点击的tab的位置跟recyclerView的可见位置做比较 取最大的 否则tab到不了指定点击的位置
                        currentPosition = Math.max(mTabPosition, currentPosition);
                        binding.tabGroup.getTabAt(currentPosition).select();
                        mTabPosition = -1;//重置下 不然最大值的话 无法滑动
                    }

                } catch (Exception e) {

                }
//                if (dy > 0 && isInitView) {
//                    isDowning = false;
//                    if (isUping) {
//                        return;
//                    }
//                    startViewInAnimator();
//                } else if (dy < 0 && isInitView) {
//                    isUping = false;
//                    if (isDowning) {
//                        return;
//                    }
//                    startViewOutAnimator();
//                }
//                isInitView = true;
                if (dy > 0) {
                    startViewOutAnimator();
                } else if (dy < 0) {
                    startViewInAnimator();
                }
            }
        });
    }

//    private boolean isInitView = false;
//    private boolean isUping = false;
//    private boolean isDowning = false;

    public void refreshCarCount(String count) {
        if (!TextUtils.isEmpty(count)) {
            binding.tvCarCountUp.setVisibility(View.VISIBLE);
            binding.tvCarCountUp.setText(count);
            binding.tvCarCount.setVisibility(View.VISIBLE);
            binding.tvCarCount.setText(count);
        } else {
            binding.tvCarCountUp.setVisibility(View.GONE);
            binding.tvCarCount.setVisibility(View.GONE);
        }
    }

    public void refreshCarCount(int count) {
        if (count != 0) {
            binding.tvCarCountUp.setVisibility(View.VISIBLE);
            binding.tvCarCountUp.setText(String.valueOf(count));
            binding.tvCarCount.setVisibility(View.VISIBLE);
            binding.tvCarCount.setText(String.valueOf(count));
        } else {
            binding.tvCarCountUp.setVisibility(View.GONE);
            binding.tvCarCountUp.setVisibility(View.GONE);
        }
    }

    @SuppressLint("SetTextI18n")
    public void showProductInfo(GoodsSkuDetailEntity data) {
        // 视频集
        videos(data);
        itemNum = data.lowestBuy;
        HashMap map = new HashMap();
        HashMap map1 = new HashMap();
        map.put("itemId", shopId);
        if (data.getItemAttr() != null && data.getItemAttr().getSku() != null) {
            for (int i = 0; i < data.getItemAttr().getSku().size(); i++) {
                for (int j = 0; j < data.getItemAttr().getSku().get(i).getList().size(); j++) {
                    if (data.getItemAttr().getSku().get(i).getList().get(j).isChecked()) {
                        map1.put(data.getItemAttr().getSku().get(i).getList().get(j).getItemParamId(), data.getItemAttr().getSku().get(i).getList().get(j).getValId());
                    }
                }
            }
        }
        if (data.getStatus() == 2) {
            setAddButton();
        }
        map.put("attribute", map1);
        viewModel.getGoodsAttributeEnabled(map);
        // 轮播图
        initBanner(data);
        companyId = data.getShopId();
        viewModel.getuserFocusCompanyStatus(companyId);
        viewModel.getCompanyModel(companyId);
        viewModel.getCompanyInformation(companyId);
        viewModel.getShopImInfo(data.getShopId());
        if (data.getItemAttr() != null && data.getItemAttr().getCheck() != null) {
            goodsSkuAdapter.setDatas(this.data.getItemAttr().getSku());
        }

        if (data.getItemAttr() != null) {
            List<SkuCheckEntity> list = data.getItemAttr().getCheck();
            StringBuilder sb = new StringBuilder();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    sb.append(list.get(i).getVal()).append(" ");
                }
            }
        }
        goodsDetailAdapter.setGoodsInfo(data);
        goodsDetailAdapter.notifyDataSetChanged();
        goodsDetailAdapter.setGoodsDetailsData(data);
        goodsDetailAdapter.notifyDataSetChanged();
    }

    @SuppressLint("SetTextI18n")
    private void videos(GoodsSkuDetailEntity data) {
        mVideos = new ArrayList<>();
        if (data.videoList != null && data.videoList.size() != 0) {
            for (GoodsSkuDetailEntity.VideoBean videoBean : data.videoList) {
                if (videoBean.type != 1) {
                    mVideos.add(videoBean.playUrl + "视频" + videoBean.playUrlImg);
                }
            }
        }
        goodsDetailAdapter.initVideoParamData(mVideos);
        goodsDetailAdapter.notifyDataSetChanged();
    }

    private void initAttributes(GoodsSkuDetailEntity data) {
        sku.clear();
        if (data.getItemAttr().getSku() != null && data.getItemAttr().getSku().size() > 0) {
            sku.addAll(data.getItemAttr().getSku());
        }
        mSelect = new ArrayList<>();
        goodsDetailAdapter.setParamShopInfo(sku);
        goodsDetailAdapter.notifyDataSetChanged();
        List<SkuCheckEntity> list = data.getItemAttr().getCheck();
        StringBuilder info = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (SkuCheckEntity skuCheckEntity : list) {
                if (!TextUtils.isEmpty(skuCheckEntity.getVal())) {
                    mSelect.add(skuCheckEntity.getVal());
                }
            }
        }
        if (data.getParams() != null && data.getParams().size() != 0) {
            for (int i = 0; i < data.getParams().size(); i++) {
                SkuItemAttrEntity skuItemAttrEntity = new SkuItemAttrEntity();
                skuItemAttrEntity.setParamData(data.getParams().get(i).k);
                SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                child.setValData(data.getParams().get(i).v);
                List<SkuItemAttrEntity.Child> childList = new ArrayList<>();
                childList.add(child);
                skuItemAttrEntity.setList(childList);
                sku.add(skuItemAttrEntity);
            }
        }
        if (sku.size() != 0) {
            for (SkuItemAttrEntity skuCheckEntity : sku) {
                info.append(skuCheckEntity.getParamData()).append("、");
            }
            mAttrAdapter = new AttrAdapter(mSelect);
            goodsDetailAdapter.setAttributes(info, mAttrAdapter);
            goodsDetailAdapter.notifyDataSetChanged();
        }
    }

    @SuppressLint("SetTextI18n")
    private void initBanner(GoodsSkuDetailEntity data) {
        List<String> urls = new ArrayList<>();
        this.data = data;
        if (data.videoList != null && data.videoList.size() != 0) {
            String key = "视频";
            for (GoodsSkuDetailEntity.VideoBean videoBean : data.videoList) {
                if (videoBean.type == 1 && !TextUtils.isEmpty(data.videoList.get(0).playUrl)) {
                    String video = data.videoList.get(0).playUrl + key +
                            data.videoList.get(0).playUrlImg + key +
                            data.videoList.get(0).time + key
                            + data.videoList.get(0).videoName;
                    urls.add(video);
                    indicator.add(new Bean(data.videoList.get(0).playUrlImg, 1));
                }
            }
        }
        if (data.getImages() != null) {
            for (String img : data.getImages()) {
                indicator.add(new Bean(img, 0));
                urls.add(img);
            }
        }
        if (indicator.size() > 0) {
            indicator.get(0).select = true;
        }
        if (indicator.size() > 1) {
            binding.imageDetailLeft.setVisibility(View.VISIBLE);
            binding.imageDetailRight.setVisibility(View.VISIBLE);
        } else {
            binding.imageDetailLeft.setVisibility(View.GONE);
            binding.imageDetailRight.setVisibility(View.GONE);
        }
        mLastIndex = indicator.size() * 10000;//初始化一个大的position可向左翻页
        if (indicator.size() == 0) {
            binding.tvPosition.setText(0 + "");
        } else {
            binding.tvPosition.setText(1 + "");
        }
        binding.tvCount.setText(indicator.size() + "");
        binding.banner.initBannerImageView(urls, false, true, 0);
        binding.banner.setStartPLAY(true);
        binding.banner.setIndicatorInterval(MIN_CLICK_DELAY_TIME);
        binding.banner.onSel(index -> {
            if (mLastIndex == index) {
                return;
            }
            if (indicator.size() == 0 || urls.size() == 0) {
                return;
            }
            if (index != 0) {
                Jzvd.releaseAllVideos();
            }
            binding.tvPosition.setText(index % indicator.size() + 1 + "");
            mLastIndex = index;
        });
    }

    /**
     * 初始化setToolBar
     */
    private void setToolBar() {
        binding.appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            binding.toolbar.setBackgroundColor(changeAlpha(getResources().getColor(R.color.white), Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange()));
            binding.toolbar.setAlpha(Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange());
        });
    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    private void showSkuPop() {
        if (!isFirst) {
            goodSSkuWindow.setData(viewModel.goodsSkuDetailEntity.get(), goodsDetailAdapter.getSuperPrice());
            isFirst = true;
        }
        // setHeight(DisplayUtil.dip2px(mContext, 450));
        goodSSkuWindow.showDownPopwindow(binding.grayLayout, true);
    }

    /***
     * 商品发布时的数据
     * @param data
     */
    public void setGoodsItemInformation(GoodsPublishEntity data) {
        this.goodsPublishEntity = data;
    }

    /***
     *
     * @param companyDetailsEntity
     */
    public void showCompanyInfoDetail(CompanyDetailsEntity companyDetailsEntity) {
        this.companyDetailsEntity = companyDetailsEntity;
    }

    /**
     * 推荐商品
     *
     * @param data
     */
    public void getRecommendList(List<RecommendListEntity> data) {
        if (data == null || data.size() == 0) {
            binding.tabGroup.addTab(binding.tabGroup.newTab().setText(titleName[0]));
            binding.tabGroup.addTab(binding.tabGroup.newTab().setText(titleName[1]));
        } else {
            binding.tabGroup.addTab(binding.tabGroup.newTab().setText(titleName[0]));
            binding.tabGroup.addTab(binding.tabGroup.newTab().setText(titleName[1]));
            binding.tabGroup.addTab(binding.tabGroup.newTab().setText(titleName[2]));
        }
        initTabLayoutTabOnclick();
        goodsDetailAdapter.setGoodsCommendData(data);
        goodsDetailAdapter.notifyDataSetChanged();
    }

    public void showCompanyInfo(MaterialCompanyEntity data) {
        companyData = data;
        goodsDetailAdapter.showCompanyInfo(data);
        goodsDetailAdapter.notifyDataSetChanged();
        this.companyNo = data.getCompanyNo();
    }

    /**
     * 商品详情（平台声明）
     *
     * @param data
     */
    public void getPlatformStatement(String data) {
        goodsDetailAdapter.showPlatformStatement(data);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.layout_attention:
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    MToast.showToast(this, "您还没有登录，请先登录");
                    return;
                }
                viewModel.userFocusCompany(companyId);
                break;
            case R.id.ll_focus:
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    MToast.showToast(this, "您还没有登录，请先登录");
                    return;
                }
                viewModel.userFocus(skuId, 1);
                break;
            case R.id.back_view_tool_bar:
            case R.id.back_view:
                finish();
                break;
            case R.id.tv_jiameng:
                if (!UserOperating.getInstance().isLogged()) {
                    jumpLogin();
                    return;
                }
                //判断是否在未展示的情况
                if (!goodsAddWindow.isShowing()) {
                    //满足条件展示
                    goodsAddWindow.showDownPopwindow(binding.grayLayout, true);
                }
                break;
            case R.id.image_icon_detail_back:
                MainActivity.start(ShopGoodsDetailActivity.this, null, getIntent().getIntExtra("type", 0));
                break;
            case R.id.tv_shop:
                MToast.showToast(ShopGoodsDetailActivity.this, "功能开发中");
                break;
            case R.id.company_info_layout:
                if (TextUtils.isEmpty(companyNo)) {
                    ToastUtil.show(ShopGoodsDetailActivity.this, "企业店铺No不能为空");
                    return;
                }
                WebsiteInfoActivity.start(ShopGoodsDetailActivity.this, companyNo, WebsiteInfoActivity.WEBSITE_FOR_COMPANY, 0, 0);
                break;
            case R.id.image_icon_detail_more:
            case R.id.tv_message:
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this, EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
                } else {
                    viewModel.itemImAlternate(shopId, 1);
                }
                break;
            case R.id.tv_add_shopping_car:
                if (certification()) {
                    if (goodsDetailAdapter.getPromoteStatus()) {
                        MToast.showToast(getActivity(), "活动未开始");
                    } else {
                        checkAddTokenView(false);
                    }
                }
                break;
            case R.id.tv_inquiry:
                //跳转到询价页面前需用户认证
                inquiryPublish();
                break;
            case R.id.tv_purchase:
                //弹起采购弹窗
                if (certification()) {
                    if (goodsDetailAdapter.getPromoteStatus()) {
                        MToast.showToast(getActivity(), "活动未开始");
                    } else {
                        checkAddTokenView(true);
                    }
                }
                break;
            case R.id.tv_shopping_car:
            case R.id.tv_shopping_car_up:
                if (certification()) {
                    viewModel.getCompanyStatus(companyData.getCompanyNo(),companyData.getCompanyName());
                }
                break;
            case R.id.rl_gg:
                showSkuPop();
                break;
            case R.id.img_share:
            case R.id.img_share_up:
                if (data == null || companyData == null) {
                    return;
                }
                String shopPath = "";
                if ("debug".equals(BuildConfig.BUILD_TYPE)) {
                    shopPath = "https://h5-shangpin.gcw.net/productDetails?id=" + shopId + "&skuid=" + skuId;
                } else if ("pre".equals(BuildConfig.BUILD_TYPE)) {
                    shopPath = "https://h5-shangpin.jingyingbang.net/productDetails?id=" + shopId + "&skuid=" + skuId;
                } else {
                    shopPath = "https://h5-shangpin.jingyingbang.com/productDetails?id=" + shopId + "&skuid=" + skuId;
                }
                String phoneNum = "";
                if (!TextUtils.isEmpty(companyData.getFixedNumber())) {
                    phoneNum = companyData.getFixedNumber();
                } else {
                    phoneNum = companyData.getPhone();
                }
                String price = "";
                if (data.isSku()) {
                    price = "¥" + data.getPriceScope() + "元/" + data.getUnit();
                } else {
                    if (data.getPrice().contains("元")) {
                        price = data.getPrice();
                    } else {
                        price = "¥" + data.getPrice() + "元/" + data.getUnit();
                    }
                }
                ShareActivity.start(ShopGoodsDetailActivity.this, shopId + skuId, data.getImages().get(0), data.getCartTitle(), price, shopPath, phoneNum);
                break;
            default:
                break;
        }
    }

    private ObjectAnimator objectAnimatorBack;
    private ObjectAnimator objectAnimatorMore;
    private ObjectAnimator objectAnimatorBack1;
    private ObjectAnimator objectAnimatorMore1;

    private void startViewOutAnimator() {
        if (isCloseing || (null != objectAnimatorBack1 && objectAnimatorBack1.isRunning())) {
            return;
        }
        if (objectAnimatorBack != null && objectAnimatorBack.isRunning()) {
            return;
        }
        int width = binding.imageIconDetailMore.getWidth();
        if (objectAnimatorMore == null) {
            objectAnimatorMore = ObjectAnimator.ofFloat(binding.imageIconDetailMore, "translationX", 0, width - 74);
            objectAnimatorMore.setDuration(500);
        }
        if (objectAnimatorBack == null) {
            objectAnimatorBack = ObjectAnimator.ofFloat(binding.imageIconDetailBack, "translationX", 0, width - 74);
            objectAnimatorBack.setDuration(500);
        }
        objectAnimatorMore.start();
        objectAnimatorBack.start();
        objectAnimatorBack.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isCloseing = true;
            }
        });
    }

    private boolean isOpening = false;
    private boolean isCloseing = false;

    private void startViewInAnimator() {
        if (isOpening || (null != objectAnimatorBack && objectAnimatorBack.isRunning())) {
            return;
        }
        if (objectAnimatorBack1 != null && objectAnimatorBack1.isRunning()) {
            return;
        }
        int width = binding.imageIconDetailMore.getWidth();
        if (objectAnimatorMore1 == null) {
            objectAnimatorMore1 = ObjectAnimator.ofFloat(binding.imageIconDetailMore, "translationX", width - 74, 0);
            objectAnimatorMore1.setDuration(500);
        }
        if (objectAnimatorBack1 == null) {
            objectAnimatorBack1 = ObjectAnimator.ofFloat(binding.imageIconDetailBack, "translationX", width - 74, 0);
            objectAnimatorBack1.setDuration(500);
        }
        objectAnimatorMore1.start();
        objectAnimatorBack1.start();
        objectAnimatorBack1.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isOpening = true;
            }
        });
    }

    private void inquiryPublish() {
        if (authentication()) {
            viewModel.getCheckUserInfo();
        }
    }

    private boolean certification() {
        if (!UserOperating.getInstance().isLogged()) {
            jumpLogin();
            return false;
        }
        int type = UserOperating.getInstance().getUserIdentity();
        if (type == 0) {
            if (Success.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))) {
                showDialog();
            } else {
                new ThreeButtonDialog.Builder(ShopGoodsDetailActivity.this)
                        .content("当前暂不支持个人用户下单，加入企\n业/认证企业后可下单")
                        .confirm("认证企业")
                        .cancel("知道了")
                        .confirmCallback(v -> {
                            RegisterActivity3.start(ShopGoodsDetailActivity.this, true);
                        }).joinCallback(v -> {
                    JoinCompanyActivity.start(getActivity());
                }).show();
            }
            return false;

        } else if (type == 1) {
            int type1 = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
            if (type1 != ACAdminDialogUtils.TYPE_NORMAL /*&& !Success.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))*/) {
                MToast.showToast(ShopGoodsDetailActivity.this, "您没有权限，请联系管理员开通");
                return false;
            }
        } else if (type == 2 || type == 3) {
            showJoinDialog();
            return false;
        }
        return true;
    }

    /***
     * 团队加入企业-提示弹窗
     * @param
     */
    private void showJoinDialog() {
        new RoundDialog.Builder(getActivity())
                .title("您没有权限")
                .content("请加入认证企业后再试")
                .cancel("我知道了")
                .confirm("加入企业")
                .confirmCallback(v -> {
                    JoinCompanyActivity.start(getActivity());
                })
                .singleBtn(false)
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    /***
     * 团队加入企业-提示弹窗
     * @param
     */
    private void showJoin2Dialog() {
        View view = View.inflate(ShopGoodsDetailActivity.this, R.layout.dialog_map_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(ShopGoodsDetailActivity.this, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvConfirm = view.findViewById(R.id.tv_confirm);
        tv_message.setText("请将身份切换到企业或者加入\n已认证的企业后再试");
        tvConfirm.setOnClickListener(v -> {
            JoinCompanyActivity.start(getActivity());
            roundCornerDialog.dismiss();
        });
        tvCancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    /***
     * 提示弹窗
     * @param
     * @param
     */
    private void showDialog() {
        View view = View.inflate(ShopGoodsDetailActivity.this, R.layout.dialog_one_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(ShopGoodsDetailActivity.this, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.GONE);
        tv_message.setText("当前暂不支持个人用户下单，请切换\n到企业身份后再试");
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("知道了");
        tv_logout_confirm.setTextColor(ShopGoodsDetailActivity.this.getResources().getColor(R.color.color_5792FD));
        tv_message.setTextColor(ShopGoodsDetailActivity.this.getResources().getColor(R.color.color_666666));
        tv_message.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_logout_confirm.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    private boolean authentication() {
        //跳转到询价页面前需用户认证
        if (!UserOperating.getInstance().isLogged()) {
            jumpLogin();
            return false;
        }
        int type = UserOperating.getInstance().getUserIdentity();
        if (type == 0) {
            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                //个人未实名认证--实名认证或加入企业
                new ThreeButtonDialog.Builder(ShopGoodsDetailActivity.this)
                        .title("温馨提示")
                        .content("您没有权限，请认证或加入企业后再试")
                        .confirmCallback(v -> {
                            //实名认证
                            AuthActivity3.start(ShopGoodsDetailActivity.this);
                        }).joinCallback(v -> {
                    //去加入企业
                    JoinCompanyActivity.start(getActivity());
                }).show();
                return false;
            }

        } else if (type == 1) {
            int type1 = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
            if (type1 != ACAdminDialogUtils.TYPE_NORMAL /*&& !Success.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))*/) {
                MToast.showToast(ShopGoodsDetailActivity.this, "您没有权限，请联系管理员开通");
                return false;
            }
        } else if (type == 2 || type == 3) {
            showJoin2Dialog();
            return false;
        }
        return true;
    }

    /***
     * 构建询价跳转参数
     */
    public void buildInquiryReleaseParam() {
        InquiryDetailsEntity inquiryDetailsEntity = new InquiryDetailsEntity();
        buildGoodsItemParam(inquiryDetailsEntity);
        buildInviteCompany(inquiryDetailsEntity);
        ARouter.getInstance().build(Constants.ARouter.AR_INQUIRY_PUBLISHING)
                .withSerializable(InquiryPublishingActivity.KEY_GOODS_DETAIL, inquiryDetailsEntity)
                .navigation();
    }

    /***
     * 构建商品信息(由于数据是多个接口数据的拼接。数据可能出错)
     * @param enquiryDetailsEntity
     */
    private void buildGoodsItemParam(InquiryDetailsEntity enquiryDetailsEntity) {
        List<GoodsItemEntity> goodsItems = new ArrayList<>();
        if (goodsPublishEntity != null) {
            GoodsItemEntity goodsItem = new GoodsItemEntity();
            goodsItem.setBrandId(goodsPublishEntity.getBrandId());
            goodsItem.setBrandName(goodsPublishEntity.getBrandName());
            goodsItem.setFcategory(goodsPublishEntity.getCid1());
            goodsItem.setFcatName(goodsPublishEntity.getCid1Name());
            goodsItem.setNum(itemNum == 0d ? "1" : String.valueOf(itemNum));
            goodsItem.setScategory(goodsPublishEntity.getCid2());
            goodsItem.setScatName(goodsPublishEntity.getCid2Name());
            goodsItem.setSort("1");
            goodsItem.setTcategory(goodsPublishEntity.getCid3());
            goodsItem.setTcatName(goodsPublishEntity.getCid3Name());
            goodsItem.setUnit(goodsPublishEntity.getUnit());

            if (data != null && data.getItemAttr() != null && data.getItemAttr().getSku() != null && data.getItemAttr().getSku().size() != 0) {
                List<GoodsAttrEntity> attrList = new ArrayList<>();
                for (SkuItemAttrEntity attrChildEntity : data.getItemAttr().getSku()) {

                    if (attrChildEntity != null && attrChildEntity.getList() != null && attrChildEntity.getList().size() != 0) {
                        for (SkuItemAttrEntity.Child child : attrChildEntity.getList()) {
                            GoodsAttrEntity attr = new GoodsAttrEntity();
                            if (child.isChecked()) {
                                attr.setParamValId(child.getValId());
                                attr.setParamValName(child.getValData());
                                attr.setParamId(attrChildEntity.getId());
                                attr.setParamName(attrChildEntity.getParamData());
                                attrList.add(attr);
                            }
                        }
                    }
                }
                goodsItem.setAttrList(attrList);
            }
            goodsItems.add(goodsItem);
        }
        enquiryDetailsEntity.setItemList(goodsItems);
    }


    /****
     * 构建供应商信息
     * @param inquiryDetailsEntity
     */
    private void buildInviteCompany(InquiryDetailsEntity inquiryDetailsEntity) {
        List<InquiryDetailsEntity.InviteCompanyList> inviteCompanyList = new ArrayList<>();
        InquiryDetailsEntity.InviteCompanyList companyListDTO = new InquiryDetailsEntity.InviteCompanyList();
        if (this.companyDetailsEntity != null) {
            companyListDTO.setSupplierName(companyDetailsEntity.getCompanyName());
            companyListDTO.setSupplier(companyDetailsEntity.getCompanyNo());
            companyListDTO.setProvinceName(companyDetailsEntity.getProvinceName());
            companyListDTO.setProvinceNo(companyDetailsEntity.getProvinceNo());
            inviteCompanyList.add(companyListDTO);
            inquiryDetailsEntity.setInviteCompanyList(inviteCompanyList);
        }
    }

    private void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(ShopGoodsDetailActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(this, EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(ShopGoodsDetailActivity.this, EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
                }
            }
        }, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code == 1000) {
                OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                oneKeyLoginEntity.setPlateform("Android");
                viewModel.oneKeyLogin(oneKeyLoginEntity);
            }
        });
    }

    public void checkAddTokenView(boolean isPurchase) {
        ShoppingCarRequest addShoppingCar = new ShoppingCarRequest();
        addShoppingCar.setItemId(shopId);
        if (!TextUtils.isEmpty(skuId)) {
            addShoppingCar.setSkuId(skuId);
        }
        addShoppingCar.setItemNum(String.valueOf(itemNum));
        //等商品详情弹框得那个值来修改
        addShoppingCar.setChoosePriceType(goodsDetailAdapter.getPriceType());
        viewModel.addShoppingCar(addShoppingCar, isPurchase);
    }

    public void checkTokenView() {
        Intent intent = new Intent();
        intent.putExtra("showPage", "FRAGMENT_SHOPPING");
        ShoppingCartActivity.start(this);
    }

    public void toLogin() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, "");
        MToast.showToast(this, "登录失效，请重新登录");
        jumpLogin();
    }

    public void setAddButton() {
        LinearLayout.LayoutParams leftParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 2);
        binding.llLeft.setLayoutParams(leftParams);
        binding.llRight.setVisibility(View.GONE);
        binding.llDown.setVisibility(View.VISIBLE);
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }


    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);

        if (UserOperating.getInstance().isLogged()) {
            viewModel.getCarCount();
        }
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    public void setuserFocusCompanyStatus() {
        setuserFocusCompanyStatus(!userFocusCompanyStatus);
    }

    public void setuserFocusCompanyStatus(boolean data) {
//        if (data == true) {
//            binding.layoutAttention.setBackgroundResource(R.drawable.bgg_lg);
//            binding.attentionImg.setImageResource(R.mipmap.attention_unnomal);
//            binding.tvAttention.setTextColor(getResources().getColor(R.color.alertdialog_gray));
//            binding.tvAttention.setText("已关注");
//        } else {
//            binding.layoutAttention.setBackgroundResource(R.drawable.bgw_lb);
//            binding.attentionImg.setImageResource(R.mipmap.attention_nomal);
//            binding.tvAttention.setText("关注");
//            binding.tvAttention.setTextColor(getResources().getColor(R.color.alertdialog_blue));
//        }
//        userFocusCompanyStatus = data;
    }

    public void setUserFocusStatus(int flag) {
        setUserFocusStatus(!userFocusStatus, flag);
    }

    public void setGoodsAttributeEnabled(List<SkuItemAttrEntity> skuItemAttrEntitys) {
        this.data.getItemAttr().setSku(skuItemAttrEntitys);
        // 商品属性
        initAttributes(data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_FOCUS) {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                MToast.showToast(this, "您还没有登录，请先登录");
                return;
            }
            viewModel.userFocus(skuId, 1);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_LOCATION) {
            Intent intent = new Intent();
            intent.setClass(getActivity(), StorageAddressActivity.class);
            intent.putExtra(StorageAddressActivity.TITLE, "地图详情");
            intent.putExtra(StorageAddressActivity.CITY, data.getStorageName());
            if (!TextUtils.isEmpty(data.getLatitude())) {
                intent.putExtra(StorageAddressActivity.LATITUDE, Double.parseDouble(data.getLatitude()));
            }
            if (!TextUtils.isEmpty(data.getLongitude())) {
                intent.putExtra(StorageAddressActivity.LONGTITUDE, Double.parseDouble(data.getLongitude()));
            }
            startActivity(intent);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_PARAM) {
            ParamsPop paramsPop = new ParamsPop(this);
            RecyclerView rv = paramsPop.mRv;
            paramsPop.mTvValue.setText(data.getCartTitle());
            rv.setLayoutManager(new LinearLayoutManager(UiUtil.getContext()));
            ParamsAdapter adapter = new ParamsAdapter(sku);
            rv.setAdapter(adapter);
            paramsPop.showPopupWindow();
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_SPECIFICATION) {
            showSkuPop();
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_COMPANY) {
            if (TextUtils.isEmpty(companyNo)) {
                ToastUtil.show(ShopGoodsDetailActivity.this, "企业店铺No不能为空");
                return;
            }
            WebsiteInfoActivity.start(ShopGoodsDetailActivity.this, companyNo, WebsiteInfoActivity.WEBSITE_FOR_COMPANY, 0, 0);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_INVITE) {
            if (!UserOperating.getInstance().isLogged()) {
                jumpLogin();
                return;
            }
            if (!MemberApplyJoin("2")) {
                return;
            }
            int accountType = UserOperating.getInstance().getUserIdentity();
            getQualityMemberBean().setApproveType("2");
            if (accountType == 0) {
                PersonInviteJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean(), false);
            } else {
                MemberInviteJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean());
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_DETAILS_JOIN) {
            if (!UserOperating.getInstance().isLogged()) {
                jumpLogin();
                return;
            }
            if (!MemberApplyJoin("1")) {
                return;
            }
            getQualityMemberBean().setApproveType("1");
            int accountType = UserOperating.getInstance().getUserIdentity();
            if (accountType == 0) {
                PersonApplyJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean(), false);
            } else {
                MemberApplyJoinActivity.start(ShopGoodsDetailActivity.this, getQualityMemberBean());
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_CALL_PHONE) {
            List<CallPhoneEntity> datas = new ArrayList<>();
            CallPhoneEntity entity = new CallPhoneEntity();
            entity.setPhone(companyData.getPhone());
            entity.setType("0");
            datas.add(entity);
            CallPhonePopWindow window = new CallPhonePopWindow(ShopGoodsDetailActivity.this);
            window.setBgView(binding.grayLayout);
            window.setData(datas);
            if (!window.isShowing()) {
                window.showDownPopwindow(binding.grayLayout, true);
            }
        }
    }

    private QualityMemberBean getQualityMemberBean() {
        if (null == bean) {
            bean = new QualityMemberBean();
            //未做非Null处理判断导致线上崩溃异常
            if (this.companyDetailsEntity != null) {
                bean.setCompanyNo(companyDetailsEntity.getCompanyNo());
                bean.setCompanyName(companyDetailsEntity.getCompanyName());
                bean.setServiceTypeName(companyDetailsEntity.getServiceTypeName());
                bean.setServiceType(companyDetailsEntity.getServiceType());
                bean.setCompanyId(companyDetailsEntity.getId());
                bean.setProvinceNo(companyDetailsEntity.getProvinceNo());
                bean.setCityNo(companyDetailsEntity.getCityNo());
                bean.setDistrictNo(companyDetailsEntity.getDistrictNo());
                bean.setAddress(companyDetailsEntity.getMapAddress());
            }
        }
        return bean;
    }

    public void setUserFocusStatus(boolean data, int flag) {
        goodsDetailAdapter.setUserFocusStatus(data, flag);
        goodsDetailAdapter.notifyDataSetChanged();
        userFocusStatus = data;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Jzvd.releaseAllVideos();
        EventBus.getDefault().unregister(this);
        if (objectAnimatorMore != null && objectAnimatorMore.isRunning()) {
            objectAnimatorMore.cancel();

        }
        if (objectAnimatorBack != null && objectAnimatorBack.isRunning()) {
            objectAnimatorBack.cancel();
        }
        objectAnimatorMore = null;
        objectAnimatorBack = null;
        binding.banner.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        GoodsWebView.removeView();
    }


    @Subscribe
    public void getCode(MessageEvent event) {
        switch (event.code) {
            case EventConstant
                    .EVENT_SHOP_DELETE:
                if ("0".equals(event.data)) {
                    refreshCarCount("");
                } else {
                    refreshCarCount(event.data.toString());
                }
                break;
            case EventConstant
                    .EVENT_HIDE_KEYBOARD:
                KeyboardUtils.hideSoftInput(this);
                break;
            case EventConstant
                    .EVENT_SELECT:
                mSelect.clear();
                String datas = (String) event.data;
                String[] s = datas.split("\t");
                for (String str : s) {
                    mSelect.add(str);
                }
                mAttrAdapter.setNewData(mSelect);
//                goodsDetailAdapter.setAttributes(mAttrAdapter);
                break;
            case EventConstant
                    .EVENT_STATE:
                int state = (int) event.data;
                if (state == 7 || state == 6) {
                    binding.banner.setStartPLAY(false);
                } else if (state == 1) {
                    binding.banner.setStopPlay();
                }
                break;
            case EventConstant
                    .EVENT_STATES:
                int states = (int) event.data;
                if (states == 0 || states == 7 || states == 6) {
                    goodsDetailAdapter.setBannerAutoPlay(true);
                } else {
                    goodsDetailAdapter.setBannerAutoPlay(false);
                }
                break;
            case EventConstant.EVENT_REFRESH_SHOP_DETAIL:
                int position = (int) event.data;
                //本地将数据的sku状态加一，
                SkuCombinationEntity skuCombinationEntity = data.getCheckedItemAttr().getList().get(position);
                skuCombinationEntity.setPromoteStatus((skuCombinationEntity.getPromoteStatus()) + 1);
                goodsDetailAdapter.notifyDataSetChanged();
                goodSSkuWindow.getSuperPrice(skuCombinationEntity.getVipPrice(), skuCombinationEntity.getPromotePrice(), skuCombinationEntity.getMoney(), skuCombinationEntity.getPromoteStatus());
                if (goodSSkuWindow.isShowing()) {
                    goodSSkuWindow.dismiss();
                }
                break;
            default:
                break;
        }
    }

    /***
     * 获取采购单列表数据
     * 根据skuId判断当前商品中是否包含在采购单中
     * 如果包含则跳转值核对订单页面
     * @param data
     */
    public void showShoppingCarDetail(List<ShoppingCarResponse> data) {
        if (data == null || data.size() == 0) {
            MToast.showToast(ShopGoodsDetailActivity.this, "采购单里没有商品，请先将商品加入采购单");
            return;
        }
        List<ShoppingCarResponse> shoppingCarResponseList = new ArrayList<>();
        boolean isExistItem = false;
        for (ShoppingCarResponse response : data) {
            List<ShoppingCarResponse.ItemsData> itemsData = response.getItems();
            ShoppingCarResponse shoppingCarResponse = new ShoppingCarResponse();
            List<ShoppingCarResponse.ItemsData> itemsData0 = new ArrayList<>();
            if (itemsData != null && itemsData.size() > 0) {
                for (ShoppingCarResponse.ItemsData itemsData1 : itemsData) {
                    if (itemsData1.getSkuId().equals(skuId) && itemsData1.getItemStatus() == 1) {
                        isExistItem = true;
                        itemsData0.add(itemsData1);
                    }

                }
            }
            if (itemsData0.size() > 0) {
                shoppingCarResponse.setPayState(response.getPayState());
                shoppingCarResponse.setImAccount(response.getImAccount());
                shoppingCarResponse.setCompanyNo(response.getCompanyNo());
                shoppingCarResponse.setCompanyName(response.getCompanyName());
                shoppingCarResponse.setCompanyId(response.getCompanyId());
                shoppingCarResponse.setIsOpenAccount(response.getIsOpenAccount());
                shoppingCarResponse.setSelfSupportTag(response.getSelfSupportTag());
                shoppingCarResponse.setItems(itemsData0);
                shoppingCarResponseList.add(shoppingCarResponse);
            }
        }
        if (isExistItem) {
            Intent intent = new Intent(ShopGoodsDetailActivity.this, StatementActivity.class);
            intent.putExtra("PURCHASE_ORDER", (Serializable) shoppingCarResponseList);
            startActivity(intent);
        } else {
            MToast.showToast(ShopGoodsDetailActivity.this, "请先将商品加入采购单再采购");
        }
    }

    protected Handler mHandler = new Handler(new Handler.Callback() {
        @SuppressLint("SetTextI18n")
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                binding.banner.mRecyclerView.smoothScrollToPosition(mLastIndex);
                binding.tvPosition.setText(mLastIndex % indicator.size() + 1 + "");
            } else if (msg.what == 1) {
                binding.banner.setStartPLAY(false);
            }
            return false;
        }
    });

    /**
     * @param joinType 1 申请 2 邀请
     * @return
     */
    private boolean MemberApplyJoin(String joinType) {
        //0--个人 1--企业 2--团队 3--组织
        int type = UserOperating.getInstance().getUserIdentity();
        if (type == 3 || type == 2) {
            //取消
            new RoundDialog.Builder(getActivity())
                    .title("")
                    .content("您当前为团队/组织身份，暂不支持该操作！")
                    .confirm("知道了")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .show();
            return false;
        } else if (type == 1) {
            //暂无地方存储是否有权限
            String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
            List<PermissionMenuEntity> data = DatalUtils.getInstance().getData(MkvUtils.CacheUserCenterMenu, CacheMarker.USER_CENTER_MENU + companyNo, new TypeToken<List<PermissionMenuEntity>>() {
            });
            if (data != null) {
                if ("1".equals(joinType)) {
                    if (UserPermissionUtils.getInstance().getMemberPermission(data, "twoLevel_huiyuanguanli", "14_shenqingguanli")) {//申请加盟
                        return true;
                    } else {
                        new RoundDialog.Builder(getActivity())
                                .title("温馨提示")
                                .content("您没有权限，请联系管理员开通！")
                                .confirm("知道了")
                                .singleBtn(true)
                                .contentGravity(Gravity.CENTER)
                                .cancelable(false)
                                .show();
                        return false;
                    }
                } else if ("2".equals(joinType)) {
                    if (UserPermissionUtils.getInstance().getMemberPermission(data, "twoLevel_huiyuanguanli", "14_yaoqingguanli")) {//邀请加盟
                        return true;
                    } else {
                        new RoundDialog.Builder(getActivity())
                                .title("温馨提示")
                                .content("您没有权限，请联系管理员开通！")
                                .confirm("知道了")
                                .singleBtn(true)
                                .contentGravity(Gravity.CENTER)
                                .cancelable(false)
                                .show();
                        return false;
                    }
                }
            } else {
                new RoundDialog.Builder(getActivity())
                        .title("温馨提示")
                        .content("您没有权限，请联系管理员开通！")
                        .confirm("知道了")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .cancelable(false)
                        .show();
                return false;
            }
        } else if (type == 0) {
            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                //已实名需要加入企业
                new ThreeButtonDialog.Builder(getActivity())
                        .title("温馨提示")
                        .content("您没有权限，请先认证为实名用户/企业用户后再试！")
                        .confirmCallback(v -> {
                            //实名认证
                            AuthActivity3.start(ShopGoodsDetailActivity.this);
                        }).joinCallback(v -> {
                    //去加入企业
                    JoinCompanyActivity.start(getActivity());
                }).cancel("知道了").show();
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * event监听登录和登出的状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LOGIN) {
            viewModel.getRecommendList(shopId, skuId);
            viewModel.getDetailModel(shopId, skuId);
            viewModel.getGoodsItemInformationById(shopId);
            viewModel.getUserFocusStatus(skuId);
            viewModel.getPlatformStatement();
            if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                viewModel.getAuthInfo();
            }
        }
    }

    public void showImWindow(List<EnquiryImAlternateEntity.CompanyCustomersDTO> companyCustomers) {
        if (companyCustomers.size() == 1) {
            if (companyCustomers.get(0) != null && !TextUtils.isEmpty(String.valueOf(companyCustomers.get(0).getImAccount()))) {
                IMUtils.getInstance().buildSingleTalking(String.valueOf(companyCustomers.get(0).getImAccount()));
            }
        } else {
            List<CallPhoneEntity> datas = new ArrayList<>();
            for (int i = 0; i < companyCustomers.size(); i++) {
                CallPhoneEntity entity = new CallPhoneEntity();
                entity.setType("1");
                entity.setPrincipalName(companyCustomers.get(i).getPrincipalName());
                entity.setImAccount(companyCustomers.get(i).getImAccount());
                entity.setImToken(companyCustomers.get(i).getImToken());
                datas.add(entity);
            }
            CallPhonePopWindow window = new CallPhonePopWindow(getActivity());
            window.setBgView(binding.grayLayout);
            window.setData(datas);
            if (!window.isShowing()) {
                window.showDownPopwindow(binding.grayLayout, true);
            }
        }
    }

}
